<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Tabs v-model:activeKey="activeKey" type="card" @change="handleTabChange">
          <TabPane v-for="v in tabsData" :key="v.key" :tab="v.title"></TabPane>
        </Tabs>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'title'">
          <div>
            <Tooltip :title="record.title">
              <div style="white-space: pre-wrap; word-break: break-all">
                {{ omitStr(record.title, 20) }}
              </div>
            </Tooltip>
            <Tag v-if="record.deleted" color="error" style="margin-right: 10px"> 已删除 </Tag>
            <Tag :color="boStatus(record.boStatus)?.dictType">
              {{ boStatus(record.boStatus)?.dictLabel }}
            </Tag>
          </div>
        </template>
        <template v-else-if="column.key === 'boType'">
          <Tag :color="boType(record.boType)?.dictType">
            {{ boType(record.boType)?.dictLabel }}
          </Tag>
        </template>
        <template v-else-if="column.key === 'reviewStatus'">
          <Tag :color="reviewStatus(record.reviewStatus)?.dictType">
            {{ reviewStatus(record.reviewStatus)?.dictLabel }}
          </Tag>
        </template>
        <template v-else-if="column.key === 'provinceName'">
          <template v-if="record.provinceName">
            {{ record.provinceName }}-{{ record.cityName }}
          </template>
          <template v-else>不限 </template>
        </template>

        <template v-else-if="column.key === 'cooperationDurationType'">
          <template
            v-if="record.cooperationDurationType === CooperationDurationTypeEnum.LimitedDate"
          >
            {{ record.cooperationDatetime }}前
          </template>
          <template v-else>长期有效</template>
        </template>

        <template v-else-if="column.key === 'userName'">
          <div class="image-text">
            <CostomAvatar :src="record.avatar" />
            <div class="text">
              <div>
                <span style="margin-right: 10px">{{ record.userName }}</span>
                <Tag v-if="record.memberLevelName" color="orange">
                  {{ record.memberLevelName }}
                </Tag>
              </div>

              <span style="white-space: normal">{{ record.companyName }}</span>
            </div>
          </div>
        </template>

        <template v-else-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '详情',
                onClick: () => toDetail(record),
              },
              {
                label: '跟进记录',
                onClick: () => toFollowRecords(record),
              },
            ]"
            :dropDownActions="[
              {
                label: '移除供需',
                onClick: () => removeBo(record),
              },

              {
                label: '关闭供需',
                onClick: () => closeBo(record),
                ifShow: record.closeAuth,
              },

              {
                label: '推广设置',
                onClick: () => promotionSettings(record),
                ifShow: !record.deleted && record.boStatus === BoStatusEnum.Active,
              },
            ]"
          >
            <template #more>
              <Button type="link">更多</Button>
            </template>
          </TableAction>
        </template>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema } from '@/components/Table';
  import { getBasicColumns } from './tableData';
  import Dictionary from '@/utils/dictionary';
  import { Avatar, Tooltip, Tag, Tabs, TabPane, Modal, Button } from 'ant-design-vue';
  import CostomAvatar from '@/components/CostomAvatar/index.vue';
  import dictionary from '@/utils/dictionary/localDicts';
  import {
    crossClubObColse,
    crossClubObList,
    crossClubObRemove,
    getCooperationType,
  } from '@/api/institution/businessOpportunitiesManage';
  import {
    BoStatusEnum,
    BoTypeEnum,
    CooperationDurationTypeEnum,
    OpReviewStatus,
  } from '@/enums/businessOpportunitiesEnum';
  import {
    IBusinessOpportunityList,
    IBusinessOpportunityReviewList,
  } from '@/api/institution/model/businessOpportunitiesManageModel';
  import { industryList } from '@/api/platform/fieldValueManage/tree';
  import { isArray } from 'lodash-es';
  import { useRouter } from 'vue-router';
  import { district } from '@/api/sys';
  import { omitStr } from '@/utils/string';
  const dicts = Dictionary.getLocalMulti(['reviewStatus', 'boType']);
  const router = useRouter();

  const tableSchemas = reactive<FormSchema[]>([
    {
      field: `keyWord`,
      label: `关键字`,
      component: 'Input',
      colProps: {
        span: 6,
      },
      componentProps: {
        placeholder: '输入供需标题/发布者姓名',
      },
    },
    {
      field: `industryCategoryCode`,
      label: `归属行业`,
      component: 'ApiCascader',
      componentProps: {
        api: industryList,
        isLoadData: false,
        initFetchParams: { size: 999 },
        labelField: 'name',
        valueField: 'id',
        isLeaf: (record) => {
          return !record.children;
        },
        showLastLabel: true,
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: 'cooperationTypeIdList',
      component: 'ApiSelect',
      label: '合作类型',
      colProps: {
        span: 6,
      },
      componentProps: {
        filterOption: false,
        api: getCooperationType,
        labelField: 'cooperationTypeName',
        valueField: 'id',
        showSearch: true,
        placeholder: '请选择',
      },
    },
    {
      field: `area`,
      label: `合作地区`,
      component: 'ApiCascader',
      componentProps: {
        api: district,
        initFetchParams: 0,
        isLoadData: true,
        asyncFetchParamKey: 'pid',
        labelField: 'name',
        valueField: 'id',
        isLeaf: (record) => {
          return record.deep >= 1;
        },
        showLastLabel: true,
        showSearch: false,
      },
      colProps: {
        span: 5,
      },
    },

    {
      field: `boType`,
      label: `供需类型`,
      component: 'Select',
      componentProps: {
        fieldNames: { label: 'dictLabel', value: 'dictValue' },
        options: dicts.boType,
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: `orgName`,
      label: `来源组织`,
      component: 'Input',
      colProps: {
        span: 6,
      },
      componentProps: {
        placeholder: '输入组织名称',
      },
    },
  ]);

  function toDetail(row: IBusinessOpportunityReviewList) {
    router.push({
      name: 'opDtail',
      query: { id: row.boInfoId },
    });
  }
  const total = ref(0);

  const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
    api: async (params) => {
      clearSelectedRowKeys();
      if (isArray(params.industryCategoryCode)) {
        params.industryCategoryCode =
          params.industryCategoryCode[params.industryCategoryCode.length - 1];
      }
      if (params.area?.length > 0) {
        params.provinceId = params.area[0];
        params.cityId = params.area[1];
      }
      if (params.cooperationTypeIdList) {
        params.cooperationTypeIdList = [params.cooperationTypeIdList];
      }
      params = { ...params, ...unref(filterInfo) };
      const res = await crossClubObList(params);
      total.value = res.total;
      return res;
    },
    columns: getBasicColumns(),
    showIndexColumn: true,
    clickToRowSelect: false,
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    formConfig: {
      labelWidth: 100,
      schemas: tableSchemas as unknown as FormSchema[],
    },
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: IBusinessOpportunityList[]) => {
      return data.map((item) => {
        return {
          ...item,
        };
      });
    },
  });

  const reviewStatus = (status: OpReviewStatus) => {
    return dictionary.reviewStatus.find((item) => item.dictValue == status);
  };

  const boStatus = (status: BoStatusEnum) => {
    return dictionary.boStatus.find((item) => item.dictValue == status);
  };

  const boType = (type: BoTypeEnum) => {
    return dictionary.boType.find((item) => item.dictValue == type);
  };

  const activeKey = ref(0);
  const filterInfo = ref<Recordable>({});
  // tabs
  const tabsData = reactive([
    {
      title: '全部',
      key: 0,
      handleReload() {
        filterInfo.value = { boStatus: undefined };
        reload({ page: 1 });
      },
    },

    {
      title: '生效中',
      key: 1,
      handleReload() {
        filterInfo.value = { boStatus: BoStatusEnum.Active };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '已过期',
      key: 2,
      handleReload() {
        filterInfo.value = { boStatus: BoStatusEnum.Expired };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '已关闭',
      key: 3,
      handleReload() {
        filterInfo.value = { boStatus: BoStatusEnum.Closed };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '已删除',
      key: 4,
      handleReload() {
        filterInfo.value = { boStatus: BoStatusEnum.Deleted };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
  ]);

  const handleTabChange = (val: number) => {
    tabsData[val].handleReload();
  };

  const closeBo = (item: IBusinessOpportunityList) => {
    Modal.confirm({
      title: '确定要关闭该供需吗？',
      content: '关闭供需',
      onOk: async () => {
        await crossClubObColse(item.id);
        Modal.success({
          title: '已关闭供需',
        });
        reload();
      },
    });
  };
  const removeBo = (item: IBusinessOpportunityList) => {
    Modal.confirm({
      title: '确定要移除该供需吗？',
      content: '供需移除后，将不再在组织成员的跨会供需库显示',
      onOk: async () => {
        await crossClubObRemove(item.id);
        Modal.success({
          title: '已移除供需',
        });
        reload();
      },
    });
  };
  const promotionSettings = (item: IBusinessOpportunityList) => {
    router.push({
      name: 'promotionSettings',
      query: { id: item.id },
    });
  };

  const toFollowRecords = (item: IBusinessOpportunityList) => {
    router.push({
      name: 'followRecords',
      query: { id: item.boInfoId },
    });
  };
</script>

<style lang="less" scoped>
  .text {
    white-space: pre-wrap;
  }

  ::v-deep .ant-table-title {
    & > div {
      display: flex;
      justify-content: space-between;
    }
  }

  .image-text {
    display: flex;
    align-items: center;
    gap: 16px;

    .text {
      flex: 1;
      display: flex;
      flex-direction: column;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>
